package x.ovo.wechat.bot.impl.http.request.core;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.util.SystemUtil;
import org.dromara.hutool.extra.qrcode.QrCodeUtil;
import org.dromara.hutool.extra.qrcode.QrConfig;
import x.ovo.wechat.bot.core.Constant;
import x.ovo.wechat.bot.core.event.SystemEvent;
import x.ovo.wechat.bot.core.http.request.ApiRequest;
import x.ovo.wechat.bot.impl.config.ClientConfig;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.function.Function;

@Slf4j(topic = "QrCodeRequest")
@RequiredArgsConstructor
public class QrCodeRequest extends ApiRequest<Void> {

    private final String uuid;
    private final String qrcodeUrl = "https://login.weixin.qq.com/qrcode/";

    @Override
    public ApiRequest<Void> build() {
        this.setUrl(qrcodeUrl + uuid);
        String osName = SystemUtil.get("os.name");
        if (osName.toLowerCase().contains("linux")) {
            log.info("请在浏览器中打开二维码链接扫码: {}", this.url);
            new SystemEvent("[login] 登录二维码链接: " + this.url).fire();
            if (ClientConfig.get().getPrintQrCode()) {
                QrConfig qrConfig = QrConfig.of().setWidth(30).setHeight(30).setBackColor(Color.BLACK).setForeColor(Color.WHITE);
                System.out.println(QrCodeUtil.generateAsAsciiArt("https://login.weixin.qq.com/l/" + this.uuid, qrConfig));
            }
        }
        return this.setHandlerType(byte[].class);
    }

    @Override
    protected Function<byte[], Void> byteArrHandler() {
        String osName = SystemUtil.get("os.name");
        if (osName.toLowerCase().contains("win") || osName.toLowerCase().contains("mac")) {
            File file = FileUtil.file(Constant.Files.CONFIG_DIR, "qrcode.png");
            return bytes -> {
                FileUtil.writeBytes(bytes, file);
                try {
                    Desktop.getDesktop().open(file);
                    log.info("请扫描屏幕上的二维码登录");
                } catch (IOException e) {
                    log.info("请在浏览器中打开二维码链接扫码: {}", this.qrcodeUrl + this.uuid);
                }
                return null;
            };
        }
        return bytes -> null;
    }
}
